#!/bin/bash

# Based on https://help.ubuntu.com/community/AutomaticSecurityUpdates

ADMIN=
LOG="/var/log/${0##*/}.log"

[ -r "/etc/default/${0##*/}" ]  && . "/etc/default/${0##*/}"

quit () {
    [ -f "$TMP" ] && rm $TMP
    exit $1
    }

error () {
    [ -f "$TMP" ] || TMP=/dev/stderr	
    report "$2 ($1)" | mailer error
    report "`date`: $2 ($1)" >> $LOG-failed
    report "Error: $2 ($1)" >&2
    quit 1
    }

report () {
    echo -e "$1"
    [ -f "$TMP" ] && sed "s/^/    /" $TMP
    }

mailer () {
    [ -n "$ADMIN" ] || return 1 
    echo "Mail -s \"apt-security-updates $1 @ `uname -nsr`\" $ADMIN" >> $TMP 2>&1
    mail -s "apt-security-updates $1 @ `uname -nsr`" $ADMIN >> $TMP 2>&1
    }

run () {
    $* >> $TMP 2>&1 || error $? "command failed: $*"
    }

TMP= && TMP=`mktemp` && [ -f "$TMP" ] || error $? "mktemp failed"
run aptitude update
run aptitude safe-upgrade -o Aptitude::Delete-Unused=false --assume-yes --target-release `lsb_release -cs`-security
grep -q "^0 " $TMP && report "No security updates available." 1>&2 && quit 0
report "Updated" | mailer success
report "\n\n[`date`]\n" >> $LOG
quit 0
